package com.example.mapper;

import com.example.entity.Package;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

public interface PackageMapper {
    List<Package> selectPackage(Package queryPackage);

    void insert(Package addPackage);

    @Select("select * from `package` where trackingNumber = #{trackingNumber}")
    Package selectByTrackingNumber(String trackingNumber);

    void updateById(Package addPackage);

    @Update("UPDATE `package` SET qr_code = #{qrCode} WHERE id = #{id}")
    void updateQrCode(@Param("id") Integer id, @Param("qrCode") String qrCode);

    @Update("update `package` set del_flag = 1 where id = #{id}")
    void deleteById(Integer id);

    @Update({
            "<script>",
            "UPDATE `package` SET state = #{state}, inboundTime = #{inboundTime} WHERE id IN",
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    void updateBatchStatus(@Param("ids") List<Integer> ids,
                           @Param("state") String state,
                           @Param("inboundTime") LocalDateTime inboundTime);

    @Update("UPDATE `package` SET pickupCode = #{pickupCode} WHERE trackingNumber = #{trackingNumber}")
    void updatePickupCodeByTrackingNumber(@Param("trackingNumber") String trackingNumber,
                                          @Param("pickupCode") String pickupCode);

    @Select("SELECT pickupCode FROM `package` WHERE trackingNumber = #{trackingNumber}")
    String selectPickupCodeByTrackingNumber(String trackingNumber);

    @Update("UPDATE package SET pickupCode = NULL WHERE trackingNumber = #{trackingNumber}")
    void clearPickupCode(String trackingNumber);

    @Update({"<script>","UPDATE package SET pickupCode = NULL WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>", "</script>"})
    void clearPickupCodes(@Param("ids") List<Integer> ids);

    @Select({
            "<script>",
            "SELECT trackingNumber FROM package WHERE id IN ",
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    List<String> selectTrackingNumbersByIds(@Param("ids") List<Integer> ids);

    @Select("SELECT COUNT(*) FROM package WHERE del_flag = 0")
    int selectPackageTotal();

    @Select("SELECT COUNT(*) FROM package WHERE del_flag = 0 AND state = '待签收'")
    int selectPendingPackageTotal();
}
